import forge from 'node-forge'

export function RSA_encrypt(data: string, RSA_public_key: string = ''): Array<string> {
    const pubKey = RSA_public_key
    if (pubKey) {
        const publicKey = forge.pki.publicKeyFromPem(pubKey)
        const RSA_config = {
            md: forge.md.sha1.create(),
            mgf: forge.mgf.mgf1.create(forge.md.sha1.create())
        }
        const default_lenght = 96 //实际上好像最长能到117
        const result: Array<string> = []
        for (let i = 0; i < Math.ceil(data.length / default_lenght); i++) {
            const temp: string = data.substring(i * default_lenght, (i + 1) * default_lenght)
            result.push(forge.util.encode64(publicKey.encrypt(temp, 'RSAES-PKCS1-V1_5', RSA_config)))
        }
        return result
    } else {
        console.log('[ERROR]RSA Encryption: No RSA publicKey found')
        return []
    }
}

export function RSA_decrypt(data: Array<string>, RSA_private_key: string = ''): string {
    const priKey = RSA_private_key
    if (priKey) {
        const privateKey = forge.pki.privateKeyFromPem(priKey)
        let result = ''
        for (const item of data) {
            const b = atob(item)
            result += privateKey.decrypt(b)
        }
        return result
    } else {
        console.log('[ERROR]RSA decryption:no RSA privateKey found')
        return '读取不到privateKey'
    }
}

export function generate_RSA_key(): { public_key: string; private_key: string } {
    const keys = forge.pki.rsa.generateKeyPair(1024)
    const public_key = forge.pki.publicKeyToPem(keys.publicKey)
    const private_key = forge.pki.privateKeyToPem(keys.privateKey)
    return {
        public_key: public_key,
        private_key: private_key
    }
}
